from fastapi import APIRouter, Query
from tortoise.expressions import Q
from app.controllers.goods.attribute import attribute_controller
from app.schemas.base import Success, SuccessExtra
from app.schemas.goods import *

attribute_router = APIRouter()
model_name = "属性"


@attribute_router.get("/list", summary=f"查看{model_name}列表")
async def list_category(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    total, data = await attribute_controller.do_list(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@attribute_router.get("/get", summary=f"查看{model_name}")
async def get_category(
        data_id: int = Query(..., description="ID"),
):
    data = await attribute_controller.do_detail(data_id=data_id)
    return Success(data=data)

@attribute_router.post("/create", summary=f"创建{model_name}")
async def create_category(
        category_in: GoodsAttributeCreate,
):
    await attribute_controller.do_create(obj_in=category_in)
    return Success(msg="创建成功")

@attribute_router.post("/update", summary=f"更新{model_name}")
async def update_category(
        category_in: GoodsAttributeUpdate,
):
    await attribute_controller.do_update(obj_in=category_in)
    return Success(msg="更新成功")

@attribute_router.delete("/delete", summary=f"删除{model_name}")
async def delete_category(
        data_id: int = Query(..., description="ID"),
):
    await attribute_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@attribute_router.get("/option", summary="获取属性列表,下拉用")
async def list_level(type:int = 1):
    level_objs = await attribute_controller.level_list(type=type)
    data = []
    for level in level_objs:
        if level:
            data.append({"label":level_objs[level],"value":level})
    return Success(data=data)
